package org.youdiversity.orm.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.youdiversity.model.hibernate.BaseEntityHibernate;
import org.youdiversity.orm.BaseDao;


public abstract class BaseDaoHibernate<T extends BaseEntityHibernate> extends
		HibernateDaoSupport implements BaseDao<T> {

	protected Class<T> entityClass;

	public BaseDaoHibernate() {
		super();
	}

	public BaseDaoHibernate(Class<T> entityClass) {
		super();
		this.entityClass = entityClass;
	}

	@Override
	public void clear() {
		getHibernateTemplate().clear();
	}

	@Override
	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
		getHibernateTemplate().flush();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void delete(final Long id) {
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				T entity = (T) session.load(entityClass, id);
				session.delete(entity);
				return null;
			}
		});
	}

	@Override
	public T get(Long id) {
		return (T) getHibernateTemplate().load(entityClass, id);
	}

	@Override
	public T load(Long id) {
		return (T) getHibernateTemplate().load(entityClass, id);
	}

	@Override
	public List<T> getAll() {
		return getHibernateTemplate().loadAll(entityClass);
	}

	@Override
	public Long save(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
		return entity.getId();
	}

	@Override
	public void update(T entity) {
		getHibernateTemplate().update(entity);
	}

	public void flush() {
		getHibernateTemplate().flush();
	}

}
